package com.ize.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ize.entity.dto.ConsultationAddDto;
import com.ize.entity.dto.huifuDto;
import com.ize.entity.pojo.*;
import com.ize.entity.vo.ConsultationVo;
import com.ize.entity.vo.DoctorConsulationVo;
import com.ize.entity.vo.LishiHuiFuVo;
import com.ize.mapper.*;
import com.ize.service.ConsultationService;
import com.ize.util.BaseContext;
import com.ize.websocket.WebSocketServer;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import springfox.documentation.spring.web.json.Json;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
@Slf4j
public class ConsultationServiceImpl extends ServiceImpl<ConsultationMapper, UserCom> implements ConsultationService {

    private final ConsultationMapper consultationMapper;
    private final DoctorComMapper doctorComMapper;
    private final UserMapper userMapper;
    private final DoctorMapper doctorMapper;
    private final WebSocketServer webSocketServer;

    /**
     * 获取留言列表
     * @return
     */
    @Override
    public List<ConsultationVo> List() {
        QueryWrapper<UserCom> wrapper = Wrappers.query();
        wrapper.eq("doctor_id",BaseContext.getCurrentId());
        wrapper.eq("state",0);//没有回复的
        List<UserCom> userComs = consultationMapper.selectList(wrapper);
        if(userComs==null||userComs.size()==0){
            return null;
        }
        //创建一个list集合存储留言数据
        List<ConsultationVo> list = new ArrayList<>();
        int i = 1;
        for (UserCom userCom : userComs) {
            log.info("第{}次userId:{}", i, userCom.getUserId());
            User user = userMapper.selectById(userCom.getUserId());
            log.info("第{}次user:{}", i,user );
            ConsultationVo consultationVo = new ConsultationVo();
            BeanUtils.copyProperties(user, consultationVo);
            consultationVo.setUser_image(user.getImage());
            consultationVo.setId(userCom.getId());
//            consultationVo.setCreateTime(userCom.getCreateTime());
            consultationVo.setTitle(userCom.getTitle());
//            consultationVo.setContent(userCom.getContent());
            consultationVo.setImage(userCom.getImage());
//            consultationVo.setUserId(userCom.getUserId());
            list.add(consultationVo);
            i++;
        }
        return list;
    }

    /**
     * 获取留言详情
     * @param id
     * @return
     */
    @Override
    public ConsultationVo getConsulation(Long id) {
        UserCom userCom = consultationMapper.selectById(id);
        User user = userMapper.selectById(userCom.getUserId());
        ConsultationVo consultationVo = new ConsultationVo();
        BeanUtils.copyProperties(user, consultationVo);
        consultationVo.setUser_image(user.getImage());
        consultationVo.setId(userCom.getId());
        consultationVo.setCreateTime(userCom.getCreateTime());
        consultationVo.setTitle(userCom.getTitle());
        consultationVo.setContent(userCom.getContent());
        consultationVo.setImage(userCom.getImage());
        consultationVo.setUserId(userCom.getUserId());
        return consultationVo;
    }

    /**
     * 回复
     * @param consultation
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void huifu(huifuDto consultation) {
        DoctorCom build = new DoctorCom().builder()
                .doctorId(BaseContext.getCurrentId())
                .userId(consultation.getUser_id())
                .content(consultation.getContent())
                .createTime(LocalDateTime.now())
                .userComId(consultation.getId())
                .build();
        doctorComMapper.insert(build);
        UserCom build1 = new UserCom().builder()
                .id(consultation.getId())
                .state(1).build();
        consultationMapper.updateById(build1);
    }

    /**
     * 删除
     * @param id
     */
    @Override
    public void delete(Long id) {
        consultationMapper.deleteById(id);
    }

    @Override
    public List<LishiHuiFuVo> listConsultation() {
        //1.查询回复内容
        QueryWrapper<DoctorCom> wrapper = Wrappers.query();
        wrapper.eq("doctor_id",BaseContext.getCurrentId());
        List<DoctorCom> doctorComs = doctorComMapper.selectList(wrapper);
        if (doctorComs == null || doctorComs.size() == 0) {
            return null;
        }
        //1.2遍历查询
        List<LishiHuiFuVo> list = new ArrayList<>();//用于存储返回结果
        for(DoctorCom doctorCom : doctorComs){
            //2.查询学生发文
            UserCom userCom = consultationMapper.selectById(doctorCom.getUserComId());
            User user = userMapper.selectById(userCom.getUserId());
            if (userCom == null){
                throw new RuntimeException("学生发问为空");
            }
            LishiHuiFuVo lishiHuiFuVo = new LishiHuiFuVo().builder()
                    .content_doctor(doctorCom.getContent())
                    .updateTime(doctorCom.getCreateTime())
                    .doctorId(BaseContext.getCurrentId())
                    .userId(userCom.getUserId())
                    .image(userCom.getImage())
                    .title(userCom.getTitle())
                    .content_user(userCom.getContent())
                    .createTime(userCom.getCreateTime())
                    .username(user.getUsername())
                    .studentId(user.getStudentId())
                    .build();
            list.add(lishiHuiFuVo);
        }
        return list;
    }

    @Override
    public List<Doctor> getDoctor(String key, String kezhen) {
        return userMapper.getDoctorInfo(key,kezhen);
    }

    @Override
    public Doctor getDoctorDetail(Long id) {
        return doctorMapper.selectById(id);
    }

    /**
     * 留言
     * @param consultationAddDto
     */
    @Override
    public void add(ConsultationAddDto consultationAddDto) {
        UserCom userCom = new UserCom();
        BeanUtils.copyProperties(consultationAddDto, userCom);
        userCom.setCreateTime(LocalDateTime.now());
        userCom.setUserId(BaseContext.getCurrentId());
        consultationMapper.insert(userCom);

        //用websocket 建立客户端连接和推送消息
        Map hashMap = new HashMap();
        hashMap.put("title",userCom.getTitle());
        hashMap.put("userid",BaseContext.getCurrentId());
        hashMap.put("time",LocalDateTime.now());

        //把信息转成Json字符转
        String jsonString = JSON.toJSONString(hashMap);
        System.out.println(jsonString);
        webSocketServer.sendToAllClient(jsonString);
    }

    @Override
    public List<DoctorConsulationVo> getConsulationByUserId() {
        QueryWrapper<DoctorCom> wrapper = Wrappers.query();
        wrapper.eq("user_id",BaseContext.getCurrentId());
        List<DoctorCom> doctorComs = doctorComMapper.selectList(wrapper);

        List<DoctorConsulationVo> list = new ArrayList<>();
        for (DoctorCom doctorCom : doctorComs) {
            Doctor user = doctorMapper.selectById(doctorCom.getDoctorId());
            DoctorConsulationVo doctorConsulationVo = new DoctorConsulationVo();
            BeanUtils.copyProperties(doctorCom, doctorConsulationVo);
            doctorConsulationVo.setDoctorname(user.getDoctorname());
            list.add(doctorConsulationVo);
        }
        return list;
    }
}
